package model

import (
	"context"
	"gorm.io/gorm"
)

type (
	Role interface {
		Insert(ctx context.Context, role string) error
		FindOne(ctx context.Context, id int64) (*AuthxRole, error)
		FindAll(ctx context.Context) ([]*AuthxRole, error)
		FindByName(ctx context.Context, name string) (*AuthxRole, error) // 新增方法
		Delete(ctx context.Context, id int64) error
		Update(ctx context.Context, id int64, role string) error
	}

	defaultRole struct {
		db *gorm.DB
	}
)

// ... 保留已有导入和接口定义 ...

func NewRole(db *gorm.DB) Role {
	return &defaultRole{
		db: db,
	}
}

func (d *defaultRole) model() *gorm.DB {
	return d.db.Model(&AuthxRole{})
}

func (d *defaultRole) Insert(ctx context.Context, role string) error {
	return d.db.Create(&AuthxRole{Role: role}).Error
}

func (d *defaultRole) FindOne(ctx context.Context, id int64) (*AuthxRole, error) {
	var result AuthxRole
	err := d.model().Where("id = ?", id).First(&result).Error

	switch err {
	case nil:
		return &result, nil
	case gorm.ErrRecordNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// 在defaultRole结构体添加实现
func (d *defaultRole) FindByName(ctx context.Context, name string) (*AuthxRole, error) {
	var result AuthxRole
	err := d.model().Where("role = ?", name).First(&result).Error

	switch err {
	case nil:
		return &result, nil
	case gorm.ErrRecordNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (d *defaultRole) FindAll(ctx context.Context) ([]*AuthxRole, error) {
	var roles []*AuthxRole
	if err := d.model().Find(&roles).Error; err != nil {
		return nil, err
	}
	return roles, nil
}

func (d *defaultRole) Delete(ctx context.Context, id int64) error {
	return d.model().Where("id = ?", id).Delete(&AuthxRole{}).Error
}

func (d *defaultRole) Update(ctx context.Context, id int64, role string) error {
	result := d.model().Where("id = ?", id).Update("role", role)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return ErrNotFound
	}
	return nil
}
